<template>
  <div class="outside"
       ref="outside">
    <div class="display-area"
         ref="content">
      <!-- 风景背景图 -->
      <img class="bg-picture"
           :src="background"
           alt="背景图片">
      <!-- 四个随机文字-->
      <span class="word-img"
            v-for="e of words"
            :key="e.index"
            :style="customStyle[e.index]"
            @click.stop="choose(e.index,$event)">{{e.word}}</span>
      <!-- 点击汉字后贾昂出现提示数字小图标 --> 
      <img class="number-tip"
           src="@/assets/images/login/digitalOne.png"
           alt="1"
           v-show="choseOrder.length>=1"
           :style="numtip[0]"
           @click.stop="withdrawChoose(0)">
      <img class="number-tip"
           src="@/assets/images/login/digitalTwo.png"
           alt="2"
           v-show="choseOrder.length>=2"
           :style="numtip[1]"
           @click.stop="withdrawChoose(1)">
      <img class="number-tip"
           src="@/assets/images/login/digitalThree.png"
           alt="3"
           v-show="choseOrder.length>=3"
           :style="numtip[2]"
           @click.stop="withdrawChoose(2)">
      <img class="number-tip"
           src="@/assets/images/login/digitalFour.png"
           alt="4"
           v-show="choseOrder.length>=4"
           :style="numtip[3]"
           @click.stop="withdrawChoose(3)">

      <div v-show="isSucceed"
           class="tip">
        <div class="tip-content">验证成功！</div>
      </div>
    </div>

    <center>
      <div class="msg"
           v-show="!isSucceed">
        <!-- <p class="action-tip">请按顺序点击以下汉字以完成验证！</p> -->
        <!-- 打乱展示顺序 -->
        <p class="action-target">请依次点击: “{{words[correctOrder[0]].word}}”,“{{words[correctOrder[1]].word}}”,“{{words[correctOrder[2]].word}}”,“{{words[correctOrder[3]].word}}”</p>
        <p class="textButton" @click.stop="changeAll()">换一张</p>
        <!-- <el-button @click.stop="changeAll()"
                   type="text"
                   style="">换一张</el-button> -->
      </div>
    </center>

    <div v-show="falseTip && chance!=0"
         class="tip">
      <div class="tip-content">验证失败</div>
    </div>
    <div v-show="chance===0"
         class="tip">
      <div class="tip-content">验证失败!</div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data () {
    return {
      bgPictures: [
        { id: '0', src: './longImg/200.jpg' },
        { id: '1', src: './longImg/201.jpg' },
        { id: '2', src: './longImg/202.jpg' },
        { id: '3', src: './longImg/203.jpg' },
        { id: '4', src: './longImg/204.jpg' },
        { id: '5', src: './longImg/205.jpg' },
        { id: '6', src: './longImg/206.jpg' },
        { id: '7', src: './longImg/207.jpg' },
        { id: '8', src: './longImg/208.jpg' }
      ],
      background: "",
      codeCharacter: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'],        //16进制数
      words: new Array(4),                                                 //储存四个汉字
      customStyle: [],                                                     //四个汉字的样式
      correctOrder: [],                                                    //正确的顺序
      choseOrder: [],                                                      //用户选择的顺序
      numtip: [],                                                          //数字的样式  用于提示用户点击了那个汉字的次序
      chance: 3,                                                           //用户还可以尝试的次数
      falseTip: false,                                                     //用户验证失败，但是仍有次数，自动刷新时的提示
      isSucceed: false,                                                    //用户验证成功
    }
  },
  // components: {
  //   SlideVerify,
  // },
  watch: {
    choseOrder: {
      deep: true,
      handler (newval) {
        //当用choseOrder的长度等于correctOrder的长度时，用户选择完毕，自动判断是否通过
        if (newval.length === this.correctOrder.length) {
          let succeed = true;
          for (let i = 0; i < this.correctOrder.length; i++) {        //逐个判断
            if (newval[i] != this.correctOrder[i]) {
              succeed = false;
            }
          }
          if (succeed) {
            this.isSucceed = true;
            this.$refs.outside.style.border = "0px";            //去除外边框
            this.verificationSuccessful()

          } else {
            this.falseTip = true;                               //显示验证失败提示
            this.chance--;                                    //可尝试机会减少
            if (this.chance > 0) {                                //重新部署
              setTimeout(() => {
                this.changeAll();
                this.falseTip = false;
              }, 1500)
            }
          }
        }
      }
    }
  },
  beforeMount () {
    this.chooseFourWords();
    this.setCorrectOrder();
  },
  mounted () {
    for (let i = 0; i < 4; i++) {
      this.customStyle.unshift(this.changeWordsStyle(3 - i));
    }
    this.background = this.chooseBGP();
  },
  methods: {
    //随机选择四个文字，加入到 words 数组
    chooseFourWords () {
      let arr = new Array();

      for (let i = 0; i < 4; i++) {
        let tempStr = '%u';

        // 随机选择第三位字符
        let temp_3 = 4 + Math.round(Math.random() * 5);
        tempStr += this.codeCharacter[temp_3];

        //随机选择第四位字符
        let temp_4;
        if (temp_3 === 4) {
          temp_4 = 14 + Math.round(Math.random());
        } else {
          temp_4 = Math.round(Math.random() * 15);
        }
        tempStr += this.codeCharacter[temp_4];

        //随机选择第五位字符
        let temp_5;
        if (temp_4 === 15 && temp_3 === 9) {
          temp_5 = Math.round(Math.random() * 10);
        } else {
          temp_5 = Math.round(Math.random() * 15);
        }
        tempStr += this.codeCharacter[temp_5];

        //随机选择第六个字符
        let temp_6;
        if (temp_3 === 9 && temp_4 === 15 && temp_5 === 10) {
          temp_6 = Math.round(Math.random() * 5);
        } else {
          temp_6 = Math.round(Math.random() * 15);
        }
        tempStr += this.codeCharacter[temp_6];

        arr.push({ index: i, word: unescape(tempStr) });
      }

      this.words = arr;
    },
    verificationSuccessful () {
      this.$emit('verificationSuccessful')
    },
    //将平面图分成四个区域，左上，左下，右上，右下；参数可以是 0,1,2,3其一 分别设置左上，右上，左下，右下 区域
    //返回一个内联样式对象
    changeWordsStyle (area) {
      if (Math.round(area) < 0 || Math.round(area) > 4) {
        return undefined;
      }

      let halfWidth = this.$refs.content.offsetWidth / 2;
      let halfHeight = this.$refs.content.offsetHeight / 2;

      let right;
      let left;
      let top;
      let bottom;

      if (area === 0 || area === 2) {
        right = halfWidth + (halfWidth - 30) * Math.random() + 'px';
      } else {
        left = halfWidth + (halfWidth - 30) * Math.random() + 'px';
      }

      if (area === 2 || area === 3) {
        top = (halfHeight - 5) * Math.random() + 'px';
      } else {
        bottom = (halfHeight - 5) * Math.random() + 'px';
      }

      let rotate = 'rotate(' + (30 + Math.random() * (-60)) + 'deg)';
      let rotateX = 'rotateX(' + (15 + Math.random() * (-30)) + 'deg)';
      let rotateY = 'rotateY(' + (15 + Math.random() * (-30)) + 'deg)';
      let scale = 'scale(' + (0.6 + Math.random()) + ',' + (0.6 + Math.random()) + ')';

      return { left, top, right, bottom, transform: rotate + " " + rotateX + " " + rotateY + " " + scale, maxWidth: '70px', maxHeight: '80px' };
    },
    //更换背景图片
    chooseBGP () {
      return this.bgPictures[Math.round(Math.random() * 8)].src;
    },
    //换一张    重新部署
    changeAll () {
      this.chooseFourWords();
      this.customStyle = [];
      for (let i = 0; i < 4; i++) {
        this.customStyle.unshift(this.changeWordsStyle(3 - i));
      }
      this.setCorrectOrder();
      this.background = this.chooseBGP();
      this.numtip = [];
      this.choseOrder = [];
    },
    //随机确定正确的点击顺序
    setCorrectOrder () {
      let s = new Set();                    //用集合来判断有没有重复
      while (s.size < 4) {
        s.add(Math.round(Math.random() * 3));
      }
      this.correctOrder = [...s];
    },
    // 用户点击汉字标签 添加或撤回     第一个参数为点击汉字在words中的index标识
    choose (index, e) {
      console.log(e);

      console.log(e.clientX);
      let wordImg = document.querySelectorAll('.word-img')[index]
      // console.log(document.querySelectorAll('.word-img')[index].style);
      // / 获取元素的计算后的样式
      var Stylestyle = window.getComputedStyle(wordImg);
      console.log(Stylestyle.top);
      console.log(Stylestyle.left);

      // outside  
      let temp = this.choseOrder.indexOf(index);
      if (temp === -1) {              //在choseOrder中找不到即是添加
        this.choseOrder.push(index);
        this.numtip.push({ left: Stylestyle.left, top: Stylestyle.top });
      } else {                      //找得到即撤回自身以及上级所选（大于等于前数字标签的撤回，可重选）
        this.choseOrder.splice(temp);
        this.numtip.splice(temp);
      }
    },
    // 点击到提示数字 撤回
    withdrawChoose (index) {
      this.choseOrder.splice(index);
      this.numtip.splice(index);
    }
  },
}
</script>

<style lang="scss" scoped>
/* 最外侧轮廓 */
.outside {
  width: 100%;
  height: 100%;
  border: 1px solid black;
  position: absolute;
  position: relative;
}
/**上方图片展示区域 */
.display-area {
  width: 100%;
  height: 75%;
  position: absolute;
  overflow: hidden;
  position: relative;
}
.bg-picture {
  width: 100%;
  height: 100%;
  z-index: 2;
}
/**汉字span */
.word-img {
  display: inline-block;
  box-sizing: border-box;
  padding: 0.1em;
  font-size: 2rem;
  font-weight: 700;
  border-radius: 0.3em;
  background: -webkit-gradient(
    linear,
    0 0,
    0 bottom,
    from(rgba(241, 210, 240, 0.644)),
    to(rgba(0, 0, 255, 0))
  );
  position: absolute;
  z-index: 4;
}
/**底部提示用户操作区 换一张按钮放置区 */
.msg {
  position: absolute;
  bottom: 0px;
  width: 100%;
  z-index: 8;
}
p {
  margin-top: 0px;
  margin-bottom: 0px;
}
.action-target {
  // font-size: 1.3em;
  // line-height: 1.6;
}
.textButton{
  text-align: center;
  color: #2c96d3;
  cursor: pointer;

}
// button {   
//   background-image: linear-gradient(
//     to right,
//     #e0eafc 0%,
//     #cfdef3 51%,
//     #e0eafc 100%
//   );
//   text-align: center;
//   width: 6rem;
//   height: 2rem;
//   text-transform: uppercase;
//   background-size: 200% auto;
//   box-shadow: 0 0 20px #eee;
//   border-radius: 10px;
//   display: block;
// }
/**数字顺序提示 */
.number-tip {
  width: 1.3rem;
  height: 1.3rem;
  background-color: #fff;
  border-radius: 90px;
  opacity: 0.9;
  z-index: 8;
  position: fixed;
}
.word-img,
button,
.number-tip:hover {
  cursor: pointer;
}
/**判断用户验证结果的提示 */
.tip {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  background-color: rgba(128, 127, 127, 0.8);
  font-size: large;
  z-index: 10;
}
.tip-content {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 2rem;
  font-weight: bolder;
  z-index: 15;
}
</style>